import datetime
import os
import time

from PySide6.QtWidgets import QFileDialog, QTextBrowser, QLineEdit, QCheckBox
from Components.COLORTool3 import COLORTOOL
from Components.AWBcheck import Parser
from Components.AE_Check4 import AEParamChecker
from PySide6.QtCore import QThread, Signal
from Components.UI.color import Ui_COLOR
import shutil
class SearchThread(QThread):
    update_text = Signal(str)  # Signal to update the text browser

    def __init__(self, folderPath, savepath, run_awb, run_ae, run_color,run_pic,hue_min, hue_max, sat_min, sat_max, threshold):
        super().__init__()
        self.folderPath = folderPath
        self.savepath = savepath
        self.run_awb = run_awb
        self.run_ae = run_ae
        self.run_color = run_color
        self.run_pic=run_pic
        self.hue_min = hue_min
        self.hue_max = hue_max
        self.sat_min = sat_min
        self.sat_max = sat_max
        self.threshold = threshold
        self.starttime = datetime.datetime.now()

    def run(self):
        if not (self.run_awb or self.run_ae or self.run_color):
            self.update_text.emit("请至少选择一个功能.")
            return
        color = COLORTOOL()
        awb = Parser()
        ae = AEParamChecker()
        # pic=COLORTOOL()
        check_result_paths = []
        all_files_normal = True  # 标志位，用于检查所有文件是否正常
        if self.hue_min:
            color.hue_min = self.hue_min
        if self.hue_max:
            color.hue_max = self.hue_max
        if self.sat_min:
            color.sat_min = self.sat_min
        if self.sat_max:
            color.sat_max = self.sat_max
        if self.threshold:
            color.threshold = self.threshold
        for root, dirs, files in os.walk(self.folderPath):
            file_names_without_extension = {os.path.splitext(f)[0] for f in files}
            has_ae = "AE" in file_names_without_extension or "TONE" in file_names_without_extension
            has_awb = "AWB" in file_names_without_extension
            has_color = 'COLOR' in file_names_without_extension



            if self.run_pic and has_color:
                path = os.path.join(self.savepath, os.path.basename(root))
                if not os.path.exists(path):
                    os.makedirs(path)
                color.setSavepath(path)
                color.setcpppath(os.path.join(root, 'COLOR.txt'))
                color. generate_and_save_image()

                endtime = datetime.datetime.now()
                print(f"[{os.path.basename(root)}]:COLOR Save Image Done！运行时间: {endtime - self.starttime}")

            if self.run_color and has_color:
                path = os.path.join(self.savepath, os.path.basename(root))
                if not os.path.exists(path):
                    os.makedirs(path)
                color.setSavepath(path)
                color.setcpppath(os.path.join(root, 'COLOR.txt'))
                color.run_read_color()
                color.check_data2()
                color.generate_summary()

                # 将 issues 列表中的内容发送到主线程
                for issue in color.issues:
                    self.update_text.emit(issue)
                endtime = datetime.datetime.now()
                print(f"[{os.path.basename(root)}]:COLOR  Done！运行时间: {endtime - self.starttime}")


            if self.run_awb and has_awb:
                path = os.path.join(self.savepath, os.path.basename(root))
                if not os.path.exists(path):
                    os.makedirs(path)
                awb.setSavepath(path)
                awb.setcpppath(os.path.join(root, 'AWB.txt'))
                awb.run()
                endtime = datetime.datetime.now()
                print(f"[{os.path.basename(root)}]:AWB    Done！运行时间: {endtime - self.starttime}")

            if self.run_ae and has_ae:
                path = os.path.join(self.savepath, os.path.basename(root))
                if not os.path.exists(path):
                    os.makedirs(path)
                ae.setSavepath(path)
                ae.setcpppath(root)
                ae.run()
                ae_pdf_path = os.path.join(path, 'AE.pdf')
                if os.path.isfile(ae_pdf_path):
                    endtime = datetime.datetime.now()
                    print(f"[{os.path.basename(root)}] AE参数不smooth.运行时间: {endtime - self.starttime}")
                else:
                    check_result_pdf_path = os.path.join(path, 'Check result.pdf')
                    if os.path.isfile(check_result_pdf_path):
                        endtime = datetime.datetime.now()
                        print(f"[{os.path.basename(root)}] AE smooth.运行时间: {endtime - self.starttime}")
                # endtime = datetime.datetime.now()
                # print(f"[{os.path.basename(root)}]:AE     Done！运行时间: {endtime - self.starttime}")


                ae_pdf_path1 = os.path.join(path, 'AE.pdf')
                check_result_pdf_path = os.path.join(path, 'Check result.pdf')

                # 检查是否存在AE.pdf文件，如果存在，说明有不正常的文件
                if os.path.isfile(ae_pdf_path1):
                    all_files_normal = False
                    # 不要break，在收集完所有的Check result.pdf后再决定是否删除

                # 如果存在Check result.pdf文件，把它的路径添加到列表中
                if os.path.isfile(check_result_pdf_path):
                    check_result_paths.append(check_result_pdf_path)

        if all_files_normal:
            # 如果所有文件都正常，创建一个新的目录来保存Check result.pdf文件
            check_result_dir = os.path.join(self.savepath, 'Check result')
            if not os.path.exists(check_result_dir):
                os.makedirs(check_result_dir)

            # 将所有Check result.pdf文件移动到新目录
            for pdf_path in check_result_paths:
                try:
                    original_folder_name = os.path.basename(os.path.dirname(pdf_path))
                    new_pdf_name = f"{original_folder_name}.pdf"
                    new_pdf_path = os.path.join(check_result_dir, new_pdf_name)
                    shutil.move(pdf_path, new_pdf_path)
                    # 检查原始文件夹是否为空
                    original_folder_path = os.path.dirname(pdf_path)
                    if not os.listdir(original_folder_path):
                        os.rmdir(original_folder_path)  # 如果为空，则删除原始文件夹
                except Exception as e:
                    print(f"Error moving file {pdf_path} to {new_pdf_path}: {e}")
        else:
            # 如果至少有一个文件不正常，删除所有的Check result.pdf文件
            for pdf_path in check_result_paths:
                try:
                    os.remove(pdf_path)
                    if not os.listdir(os.path.dirname(pdf_path)):
                        os.rmdir(os.path.dirname(pdf_path))  # 如果为空，则删除文件夹
                except Exception as e:
                    print(f"Error deleting file {pdf_path}: {e}")

        self.update_text.emit("完成")

class FileSearcher:
    def __init__(self, lineEdit: QLineEdit, textBrowser: QTextBrowser, awb_checkbox: QCheckBox, ae_checkbox: QCheckBox, color_checkbox: QCheckBox,color_piccheckbox:QCheckBox,color_ui:Ui_COLOR):
        self.lineEdit = lineEdit
        self.textBrowser = textBrowser
        self.awb_checkbox = awb_checkbox
        self.ae_checkbox = ae_checkbox
        self.color_checkbox = color_checkbox
        self.color_piccheckbox=color_piccheckbox
        self.color_ui = color_ui
    def browseFolder(self):
        folderPath = QFileDialog.getExistingDirectory(None, 'Select Folder')
        if folderPath:
            self.lineEdit.setText(folderPath)

    def saveFolder(self, lineEdit_2: QLineEdit):
        self.savepath = QFileDialog.getExistingDirectory(None, 'Select Folder')
        if self.savepath:
            lineEdit_2.setText(self.savepath)

    def runSearch(self):
        self.textBrowser.clear()
        folderPath = self.lineEdit.text()
        self.textBrowser.append("正在检索文件....\n")

        if folderPath:
            run_awb = self.awb_checkbox.isChecked()
            run_ae = self.ae_checkbox.isChecked()
            run_color = self.color_checkbox.isChecked()
            run_pic=self.color_piccheckbox.isChecked()

            hue_min = float(self.color_ui.lineEdit.text()) if self.color_ui.lineEdit.text() else None
            hue_max = float(self.color_ui.lineEdit_2.text()) if self.color_ui.lineEdit_2.text() else None
            sat_min = float(self.color_ui.lineEdit_3.text()) if self.color_ui.lineEdit_3.text() else None
            sat_max = float(self.color_ui.lineEdit_4.text()) if self.color_ui.lineEdit_4.text() else None
            threshold = float(self.color_ui.lineEdit_5.text()) if self.color_ui.lineEdit_5.text() else None

            self.searchThread = SearchThread(folderPath, self.savepath, run_awb, run_ae, run_color,run_pic,hue_min,
                                             hue_max, sat_min, sat_max, threshold)
            self.searchThread.update_text.connect(self.updateTextBrowser)
            self.searchThread.start()
        else:
            self.textBrowser.setText("Please enter a valid folder path.")

    def updateTextBrowser(self, text):
        self.textBrowser.append(text)

